package com.amado.course35Concurrent;

import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2018\3\18 0018.
 */
public class S18ShutdownShutdownNow {
	//5秒后全部回收线程
	static ExecutorService executorService = new ThreadPoolExecutor(2, 6, 5, TimeUnit.SECONDS,
			new LinkedBlockingDeque<Runnable>(2000));

	static AtomicInteger atomicInteger = new AtomicInteger();
	public static void main(String[] args) throws ExecutionException, InterruptedException {
		print();
		userFuture();
	}

	public static void print() {
		ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("atomicInteger"  +atomicInteger.get());
					System.out.print("当前活动"+threadPoolExecutor.getActiveCount());
					System.out.print(" 总线程"+threadPoolExecutor.getMaximumPoolSize());
					System.out.println(" 池中的当前线程数"+threadPoolExecutor.getPoolSize());
				}
			}
		}).start();
	}

	public static void userFuture() throws ExecutionException, InterruptedException {
//		ExecutorService executorService = Executors.newFixedThreadPool(2);
		// 初始化2个线程，调用 submit如果线程不够就加一个，但最多是8个，超8个线程报异常，闲置时间5分钟就回收线程
		// Future future = new FutureTask(new Thraed3(search));
		for (int i = 0; i < 1000; i++) {
			executorService.submit(new Runnable() {
				@Override
				public void run(){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName());
					atomicInteger.getAndIncrement();
				}
			});
		}
		System.out.println("shutdown begin");
		executorService.shutdown();
		System.out.println("shutdown now");

	}

}
